#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct student{
	char* name;
	int average;
}STUDENT; //WHY CAPS?!


STUDENT *students_load(FILE *fp, short int *size)
{
	STUDENT *ret;
	short int len;
	fread(size, sizeof(short int), 1, fp);
	ret = malloc(sizeof(STUDENT) * (*size));
	for(int i=0;i<(*size);i++)
	{
		fread(&len, sizeof(short int), 1, fp);
		ret[i].name = malloc(sizeof(char)*(len+1));
		fread(ret[i].name, sizeof(char), len, fp);
		ret[i].name[len] = '\0';
		fread(&(ret[i].average), sizeof(int), 1, fp);

	}


	return ret;
}
STUDENT **students_ptr(STUDENT *arr, short int size)
{
	STUDENT **ret;
	ret = malloc(sizeof(STUDENT *)*size);
	for(int i=0;i<size;i++)
		ret[i] = arr+i;
	return ret;
}

int student_cmpr(const void *st1, const void *st2)
{
	return ((STUDENT *)(st2))->average - ((STUDENT *)(st1))->average;
}

int main(int argc, char *argv[])
{
	short int size;
	char *newfile;
	FILE *fp;
	STUDENT *arr;
	STUDENT **arr_sort;
	int ind;
	if(argc<2)
	{
		printf("usage: %s <filename>\n", argv[0]);
		return 1;
	}
	fp = fopen(argv[1], "rb");
	arr = students_load(fp, &size);
	arr_sort = students_ptr(arr, size);
	qsort(arr_sort, size , sizeof(STUDENT *), student_cmpr);
	newfile = malloc(sizeof(char) * (strlen(argv[1]) + 5));
	sprintf(newfile, "%s.ind", argv[1]);
	newfile[strlen(argv[1]) + 4] = '\0';
	fclose(fp);

	fp = fopen(newfile, "wb");
	for(int i=0;i<size;i++)
	{
		ind = (int)(arr_sort[i] - &(arr[0]));
		fwrite(&ind, sizeof(int), 1, fp);
	}

	for(int i=0;i<size;i++)
		printf("%d: name: %s, average: %d\n", i, arr[i].name, arr[i].average);
	printf("Sorted array:\n");
	for(int i=0;i<size;i++)
		printf("%d: name: %s, average: %d\n", i, arr_sort[i]->name, arr_sort[i]->average);
	fclose(fp);
	return 0;
}
